package com.github.glomadrian.materialanimatedswitch.painter;

import com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitchState;
import com.github.glomadrian.materialanimatedswitch.observer.BallMoveObservable;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;

import java.util.Observable;
import java.util.Observer;

public class BasePainter implements SwitchInboxPinnedPainter, Observer {
    private Paint paint;
    private int bgColor;
    private int toBgColor;
    private int padding;
    private int height;
    private int width;
    private Paint toBgPainter;
    private AnimatorValue colorAnimator;
    private BallMoveObservable ballMoveObservable;

    public BasePainter(int bgColor, int toBgColor, int padding,
                       BallMoveObservable ballMoveObservable) {
        this.bgColor = bgColor;
        this.toBgColor = toBgColor;
        this.padding = padding;
        this.ballMoveObservable = ballMoveObservable;
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(new Color(bgColor));
        paint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
        paint.setAntiAlias(true);

        toBgPainter = new Paint();
        toBgPainter.setColor(new Color(toBgColor));
        toBgPainter.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
        toBgPainter.setAntiAlias(true);
        toBgPainter.setAlpha(0);

        initColorAnimator();
        ballMoveObservable.addObserver(this);
    }

    private void initColorAnimator() {
        colorAnimator = new AnimatorValue();
        colorAnimator.setDuration(100);
        colorAnimator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                toBgPainter.setAlpha(v);
            }
        });
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawLine(padding, height / 2, width - padding, height / 2, paint);
        canvas.drawLine(padding, height / 2, width - padding, height / 2, toBgPainter);
    }

    @Override
    public int getColor() {
        return bgColor;
    }

    @Override
    public void setColor(int color) {
    }

    @Override
    public void onSizeChanged(int height, int width) {
        this.height = height;
        this.width = width;
        paint.setStrokeWidth(height / 2);
        toBgPainter.setStrokeWidth(height / 2);
    }

    @Override
    public void setState(MaterialAnimatedSwitchState state) {
    }

    @Override
    public void update(Observable observable, Object o) {
        float value = ((BallMoveObservable) observable).getBallAnimationValue();

        toBgPainter.setAlpha(value);
    }
}
